package com.java.blog.utils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author TaoYu
 * @Describe:不需要手动释放连接，2.5后采取了try catch resource 模式，自动释放 简单封装，其他的根据需要自行封装
 */
public class RedisUtil {

	private RedisUtil() {
	}

	private static JedisPool jedisPool;// 连接池
	static {
		// 1、获取配置
		PropertiesUtil p = new PropertiesUtil("common.properties");
		// 2、初始化相关配置
		String host = p.getString("redis.host");// 主机
		Integer port = p.getInteger("redis.port");// 端口
		Integer timeout = p.getInteger("redis.timeout");// 连接超时
		String password = p.getString("redis.pass");// 密码
		// 3、获取默认配置，并初始化连接池
		JedisPoolConfig config = initPoolConfig(p);
		jedisPool = new JedisPool(config, host, port, timeout, password);
	}

	/**
	 * @Describe：初始化连接池配置
	 */
	private static JedisPoolConfig initPoolConfig(PropertiesUtil p) {
		JedisPoolConfig config = new JedisPoolConfig();
		Integer minIdle = p.getInteger("redis.minIdle");
		Integer maxIdle = p.getInteger("redis.maxIdle");
		Integer maxTotal = p.getInteger("redis.maxTotal");
		Long maxWait = p.getLong("redis.maxWait");
		Boolean testOnBorrow = p.getBoolean("redis.testOnBorrow");
		config.setMinIdle(minIdle);
		config.setMaxIdle(maxIdle);
		config.setMaxTotal(maxTotal);
		config.setMaxWaitMillis(maxWait);
		config.setTestOnBorrow(testOnBorrow);
		return config;
	}

	/**
	 * @Describe:是否存在
	 */
	public static Boolean exists(String key) {
		try (Jedis jedis = jedisPool.getResource()) {
			return jedis.exists(key);
		}

	}

	/**
	 * @Describe:普通新增
	 */
	public static String set(String key, String value) {
		try (Jedis jedis = jedisPool.getResource()) {
			return jedis.set(key, value);
		}
	}

	/**
	 * @Describe:普通获取数据
	 */
	public static String get(String key) {
		try (Jedis jedis = jedisPool.getResource()) {
			return jedis.get(key);
		}
	}

	/**
	 * @Describe:删除数据
	 */
	public static Long del(String key) {
		try (Jedis jedis = jedisPool.getResource()) {
			return jedis.del(key);
		}
	}
}
